package com.epfresh.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;

import com.epfresh.R;
import com.epfresh.adapter.CommentGoodsAdapter;
import com.epfresh.adapter.CommentGoodsAdapter.WriteContent;
import com.epfresh.api.entity.FileUploadResponse;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.AppActivity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.ucrop.PhotoCore;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.L;
import com.epfresh.api.utils.T;
import com.epfresh.bean.CommentLoad;
import com.epfresh.bean.Images;
import com.epfresh.global.BaseActivity;
import com.google.gson.Gson;

import java.io.File;
import java.util.ArrayList;

public class CommentGoodsActivity extends BaseActivity implements WriteContent{
	private ListView mListView;
	private ArrayList<CommentLoad.StoreListBean.StoreItemListBean> goodsList = new ArrayList<>();
	private CommentLoad.StoreListBean storeBean;// = new CommentLoad.StoreListBean();

	CommentGoodsAdapter adapter;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (savedInstanceState != null) {
			getIntent().putExtra("storeBean",savedInstanceState.getSerializable("storeBean"));
		}
		initView();
		if(getIntent().getSerializableExtra("storeBean")!=null){
			storeBean = (CommentLoad.StoreListBean)getIntent().getSerializableExtra("storeBean");
			goodsList.addAll(storeBean.getStoreItemList());
			adapter.storeName = storeBean.getStoreName();
			if(goodsList==null||goodsList.size()<=0){
				T.toast("信息有误稍后重试");
				finish();
			}else {
				adapter.notifyDataSetChanged();
			}
		}

        initPhotoCore();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putSerializable("storeBean",storeBean);
		super.onSaveInstanceState(outState);
	}

	void initView(){
		setContentView(R.layout.activity_comment_new);
		mListView = (ListView) findViewById(R.id.lv_comment_new);
		baseback.setVisibility(View.VISIBLE);
		rightbtn.setText("提交");
		toolbarTitle.setText("评价商品");
		rightbtn.setVisibility(View.VISIBLE);
		adapter = new CommentGoodsAdapter(this, goodsList);
		mListView.setAdapter(adapter);
		adapter.setOnItemClickListener(this);
		adapter.setWriteContent(this);
	}
    String filePath = FileUtil.getImgCacheDir() + "/" + "comment";

	public void onClick(View v) {
		if(v.getId()==R.id.baseback) {
			finish();
			return;
		}
		if(v.getId()==R.id.rightbtn) {
			submit();
			return;
		}
        positionItem = (Integer) v.getTag(R.id.item_key_position);
        filePath += ("_" + System.currentTimeMillis());

		switch (v.getId()) {
			case R.id.pu_cover_1:
                positionPic = 0;
                photoCore.showPhotoDialog(Uri.fromFile(new File(filePath)), filePath,false);
                break;
            case R.id.pu_cover_2:
                positionPic = 1;
                photoCore.showPhotoDialog(Uri.fromFile(new File(filePath)), filePath,false);
                break;
			case R.id.pu_cover_3:
                positionPic = 2;
                photoCore.showPhotoDialog(Uri.fromFile(new File(filePath)), filePath,false);
				break;
			case R.id.v_top_1:
				goodsList.get(positionItem).getImgList().remove(0);
				adapter.notifyDataSetChanged();
				break;
			case R.id.v_top_2:
				goodsList.get(positionItem).getImgList().remove(1);
				adapter.notifyDataSetChanged();
				break;
			case R.id.v_top_3:
				goodsList.get(positionItem).getImgList().remove(2);
				adapter.notifyDataSetChanged();
				break;

		}
	}
    int positionItem;
	int positionPic;

	public void submit(){
		Intent intent = new Intent();
		intent.putExtra("storeBean",storeBean);
		setResult(RESULT_OK, intent);
		finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (photoCore != null){
			photoCore.onResult(requestCode, resultCode, data);
		}
	}


    PhotoCore photoCore;
	Images imagesCurrent = null;

    PhotoCore.PhotoResult photoResult = new PhotoCore.PhotoResult() {
        public void onSuccess(String path) {
            if(goodsList.get(positionItem).getImgList()==null){
                Images images = new Images();
                images.setFilePath(path);
                ArrayList list = new ArrayList<Images>();
                list.add(images);
                goodsList.get(positionItem).setImgList(list);
                adapter.notifyDataSetChanged();

				imagesCurrent = images;


            }else
            if(goodsList.get(positionItem).getImgList().size()==0){
                Images images = new Images();
                images.setFilePath(path);
                goodsList.get(positionItem).getImgList().add(images);
                adapter.notifyDataSetChanged();
				imagesCurrent = images;
            }else
            if(goodsList.get(positionItem).getImgList().size()>positionPic){
                Images images = goodsList.get(positionItem).getImgList().get(positionPic);
                images.setFilePath(path);
                adapter.notifyDataSetChanged();
				imagesCurrent = images;

            } else {
                Images images = new Images();
                images.setFilePath(path);
                goodsList.get(positionItem).getImgList().add(images);
                adapter.notifyDataSetChanged();
				imagesCurrent = images;
            }
			photoCore.uploadImage((AppActivity)mContext,Uri.fromFile(new File(filePath)).getPath(),imagesCurrent,uploadListener);
        }

        public void onFail(String msg) {

        }

        public void onReupload() {

        }
    };

	//用于记录图片状态,0,没有图片,1,上传中,2,上传失败,3,上传成功
	OnRequestListener<FileUploadResponse> uploadListener = new OnRequestListener<FileUploadResponse>() {
		@Override
		public FileUploadResponse jsonToObj(String responseStr) {
			return new Gson().fromJson(responseStr, FileUploadResponse.class);
		}

		@Override
		public void onFail(int failCode, Object arg, Object tag) {
			hideProgressDialog();
			imagesCurrent.setType(2);
			L.e("upload", "upload image fail");

		}

		@Override
		public void onResponseError(int failCode, Object arg, Object tag) {
			hideProgressDialog();
			imagesCurrent.setType(2);
			L.e("upload", "upload image server fail");
		}

		@Override
		public void onStart(Object tag) {
			imagesCurrent.setType(1);
			showProgressDialog();
		}

		@Override
		public void onResponse(ResponseEntity<FileUploadResponse> response, Object tag) {
			hideProgressDialog();
			imagesCurrent.setType(3);
			imagesCurrent.setId(""+response.getResponseElement().getId());
/*			Log.e("response",response.toString());
			Log.e("response",response.toString());

				for(int j=0;j<goodsList.size();j++){
					CommentLoad.StoreListBean.StoreItemListBean childBean =goodsList.get(j);
					String affixs = new String();
					for(int m=0;childBean.getImgList()!=null&&m<childBean.getImgList().size();m++){
						affixs += (childBean.getImgList().get(m).getId() + ",");
					}
					childBean.setAffixs(affixs);
					Log.e("goods"+j,"___"+affixs);

			}*/

		}
	};

    private void initPhotoCore() {
        photoCore = new PhotoCore(photoResult, this);
        photoCore.setRatio(4, 3);
        photoCore.setResultHeight(500);
        photoCore.setResultWidth(500);

    }
	@Override
	public void write(int position, String content){
    	goodsList.get(position).setContent(content);
    	//adapter.notifyDataSetChanged();
		Log.e("position content",goodsList.get(position).getContent());
	}
}
